package com.example.photography.Activity;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.example.photography.Model;
import com.example.photography.R;
import com.example.photography.adapter.TextAdapter;
import com.example.photography.common.AppNetConfig;
import com.example.photography.common.BaseActivity;
import com.example.photography.retrofit.ApiService;
import com.example.photography.util.SharePreference;
import com.example.photography.util.UIUtils;
import com.example.photography.util.Util;
import com.example.photography.view.ZFlowLayout;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.inject.Inject;

import butterknife.BindView;
import butterknife.ButterKnife;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class Group_Search extends BaseActivity {
    //注入动态代理实例对象
    @Inject
    ApiService apiService;
    private final int RG_FAULT = 0;
    private final int RC_SEARCH = 1;
    private final int RQ_SUCCESS = 2;
    private final int RQ_PROBLEM = 3;
    private final int RQ_EMPTYE = 4;
    private final int INTERVAL = 2000; //输入时间间隔为2000毫秒
    @BindView(R.id.iv_back)
    ImageView ivBack;
    @BindView(R.id.tv_affirm)
    TextView tvAffirm;
    @BindView(R.id.et_search)
    EditText etSearch;
    @BindView(R.id.iv_delete)
    ImageView ivDelete;
    @BindView(R.id.rl_item)
    RelativeLayout rlItem;
    @BindView(R.id.zl_history)
    ZFlowLayout zlHistory;
    @BindView(R.id.lv_result)
    ListView lvResult;

    private String message;
    private List<String> groups = new ArrayList<>();
    private TextAdapter textAdapter;
    private List<String> groups_select = new ArrayList<>();//选中的圈子

    @Override
    protected void initData() {
        Intent intent = getIntent();
        Bundle bundle = intent.getBundleExtra("data");
        if (bundle != null && bundle.getStringArrayList("groups") != null) {
            groups_select = bundle.getStringArrayList("groups");
        }
        initView();
        initListen();
    }

    private void initListen() {
        ivBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                removeCurrentActivity();
            }
        });
        etSearch.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                    mHandler.sendEmptyMessageDelayed(RC_SEARCH, INTERVAL);
//                    rlItem.setVisibility(View.INVISIBLE);
//                    lvResult.setVisibility(View.VISIBLE);
//                    String searchKey = etSearch.getText().toString().trim();
//                    if (!searchKey.equals("")) {
//                        mHandler.sendEmptyMessageDelayed(RC_SEARCH, INTERVAL);
//                    } else {
//                        Util.showToast(Group_Search.this, "搜索内容为空~");
//                    }
                    return true;
                }
//                rlItem.setVisibility(View.INVISIBLE);
//                lvResult.setVisibility(View.INVISIBLE);
                return false;
            }
        });
        lvResult.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int positon, long l) {
                save(groups.get(positon));
                if (!groups_select.contains(groups.get(positon))) {
                    groups_select.add(groups.get(positon));
                }
                initHistory();
            }
        });
        etSearch.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
//                lvResult.setVisibility(View.VISIBLE);
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
            }

            @Override
            public void afterTextChanged(Editable s) {
                if (mHandler.hasMessages(RC_SEARCH)) {
                    mHandler.removeMessages(RC_SEARCH);
                }
                if (!TextUtils.isEmpty(etSearch.getText())) {
                    mHandler.sendEmptyMessageDelayed(RC_SEARCH, INTERVAL);
                }
            }
        });
        ivDelete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                SharePreference.cleanHistory("group_history");
                initHistory();
            }
        });
        tvAffirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent();
                intent.putStringArrayListExtra("groups", (ArrayList<String>) groups_select);
                setResult(RESULT_OK, intent);
                removeCurrentActivity();
            }
        });
    }

    private void initView() {
        textAdapter = new TextAdapter(groups, this);
        lvResult.setAdapter(textAdapter);
        search_user(AppNetConfig.find_groups, "");
        initHistory();
    }


    private void initHistory() {
        final String[] data = getHistoryList();
        ViewGroup.MarginLayoutParams layoutParams = new ViewGroup.MarginLayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        layoutParams.setMargins(10, 10, 10, 10);
        zlHistory.removeAllViews();

        for (int i = 0; i < data.length; i++) {
            if ((data[i]).equals("")) {
                return;
            }
            final int j = i;
            //添加分类块
            View paramItemView = getLayoutInflater().inflate(R.layout.item_search, null);
            RelativeLayout rl_text = paramItemView.findViewById(R.id.rl_text);
            TextView keyWordTv = paramItemView.findViewById(R.id.tv_content);
            keyWordTv.setText(data[j]);
            zlHistory.addView(paramItemView, layoutParams);
            if (groups_select.contains(data[j])) {
                rl_text.setBackgroundResource(R.drawable.bg_rl_black);
                keyWordTv.setTextColor(-50027);
            }
            keyWordTv.setOnClickListener(new View.OnClickListener() {
                @SuppressLint("ResourceAsColor")
                @Override
                public void onClick(View v) {
                    if (groups_select.contains(keyWordTv.getText().toString())) {
                        groups_select.remove(keyWordTv.getText().toString());
                        rl_text.setBackgroundResource(R.drawable.bg_rl_gray);
                        keyWordTv.setTextColor(Color.parseColor("#574E5F"));

                    } else {
                        groups_select.add(keyWordTv.getText().toString());
                        rl_text.setBackgroundResource(R.drawable.bg_rl_black);
                        keyWordTv.setTextColor(-50027);
                    }
                }
            });
        }

    }

    public static void save(String keyword) {
        // 获取搜索框信息
        SharedPreferences mysp = UIUtils.getContext().getSharedPreferences("group_history", 0);
        String old_text = mysp.getString("history", "");
        // 利用StringBuilder.append新增内容，逗号便于读取内容时用逗号拆分开
        StringBuilder builder = new StringBuilder(old_text);
        builder.append(keyword + ",");

        // 判断搜索内容是否已经存在于历史文件，已存在则不重复添加
        if (!old_text.contains(keyword + ",")) {
            SharedPreferences.Editor myeditor = mysp.edit();
            myeditor.putString("history", builder.toString());
            myeditor.apply();
        }
    }

    public static String[] getHistoryList() {
        // 获取搜索记录文件内容
        SharedPreferences sp = UIUtils.getContext().getSharedPreferences("group_history", 0);
        String history = sp.getString("history", "");
        // 用逗号分割内容返回数组
        String[] history_arr = history.split(",");
        // 保留前10条数据
        if (history_arr.length > 10) {
            String[] newArrays = new String[10];
            System.arraycopy(history_arr, 0, newArrays, 0, 50);
        }
        return history_arr;
    }

    private void search_user(String url, String value) {
        //开启等待动画
//        LoadingDialog.getInstance(Search_Activity.this).show();

        OkHttpClient client = new OkHttpClient();
        //POST请求
        FormBody formBody = new FormBody.Builder()
                .add("value", value)
                .build();
        Request request = new Request.Builder()
                .url(url)
                .post(formBody)                //默认就是GET请求就可以不写，这里是post
                .build();

        Call call = client.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, final IOException e) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        message = "后台君好像生病了~";
                        mHandler.sendEmptyMessageDelayed(RG_FAULT, 0);//关闭等待动画，0延时
                    }
                });
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String jsonString = response.body().string();
                Log.e("oooooooooooooooooooo", jsonString);
                try {
                    JSONObject jsonObject = new JSONObject(jsonString);
                    int result = Integer.parseInt(jsonObject.getString("status"));
                    message = jsonObject.getString("msg");
                    groups.clear();
                    if (result == 202) {//查询成功
                        JSONArray resultJsonArray = jsonObject.getJSONArray("data");
                        for (int i = 0; i < resultJsonArray.length(); i++) {
                            //循环遍历，获取json数据中data数组里的内容
                            JSONObject Object = resultJsonArray.getJSONObject(i);
                            String group = Object.getString("group_id");
                            groups.add(group);
                        }
                        mHandler.sendEmptyMessageDelayed(RQ_SUCCESS, 0);//关闭等待动画，0延时
                    } else if (result == 406) {
                        mHandler.sendEmptyMessageDelayed(RQ_EMPTYE, 0);//关闭等待动画，0延时
                    } else {
                        mHandler.sendEmptyMessageDelayed(RQ_PROBLEM, 0);//关闭等待动画，0延时
                    }

                } catch (JSONException e) {
                    e.printStackTrace();
                    message = e.toString();
                    mHandler.sendEmptyMessageDelayed(1, 0);//关闭等待动画，0延时

                }
            }
        });
    }

    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case RG_FAULT://没网
                    Util.showToast(Group_Search.this, message);
                    break;
                case RC_SEARCH://联网请求
                    Util.showToast(Group_Search.this, "内容更新，联网请求~");
                    Model.getInstance().getGlobalThreadPool().execute(new Runnable() {
                        @Override
                        public void run() {
                            search_user(AppNetConfig.find_groups, etSearch.getText().toString().trim().toString());
                        }
                    });

                    break;
                case RQ_SUCCESS:
//                    lvResult.setVisibility(View.VISIBLE);
                    textAdapter.notifyDataSetChanged();
                    break;
                case RQ_EMPTYE:
                    Util.showToast(Group_Search.this, message);
                    break;
            }
        }
    };

    @Override
    protected int getLayoutId() {
        return R.layout.activity_group_search;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }
}
